﻿using DAL;
using DAL.Entities;
using DAL.JSGN;
using DAL.RYGL;
using DAL.Unit;
using DAL.YQZS;
using Models;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace BLL.YQZS
{
    public class YqdataBLL
    {
        private readonly DataContext _dataContext;
        private readonly YqdataDAL _yqdataDAL;

        public YqdataBLL()
        {
            _dataContext = new DataContext();
            _yqdataDAL = new YqdataDAL(_dataContext);
        }

        public Yqdata getYqdata(int type, DateTime time)
        {
            var data = _yqdataDAL.GetYqdata(type, time);
            if (data == null)
            {
                data = rqData(type);
            }
            return data;
        }

        private Yqdata rqData(int type)
        {
            WebClient wc = new WebClient();
            string rqUrl = type == 0 ? "http://api.tianapi.com/txapi/ncov/index?key=0520a8688ad94b7ed67bbc0373250b65" : "http://api.tianapi.com/txapi/ncovcity/index?key=0520a8688ad94b7ed67bbc0373250b65";
            byte[] bt = wc.DownloadData(rqUrl);
            if (bt != null && bt.Count() > 0)
            {
                string content = Encoding.UTF8.GetString(bt);
                JObject jo = JObject.Parse(content);
                if (jo["code"] != null && jo["code"].ToString() == "200")
                {
                    var e = new Yqdata()
                    {
                        Id = Guid.NewGuid(),
                        CreateTime = DateTime.Now,
                        JsonObj = content,
                        Type = type
                    };
                    _yqdataDAL.CreateAsync(e);
                    _yqdataDAL.SaveChanges();
                    return e;
                }
                return null;
            }
            return null;
        }
    }
}
